import 'dart:convert';

import 'package:bot_toast/bot_toast.dart';
import 'package:easy_read_comic/internal/api/common_api.dart';
import 'package:easy_read_comic/internal/http_client.dart';
import 'package:dio/dio.dart';
import 'package:logger/logger.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../models/app_model.dart';
import '../models/user_model.dart';

typedef AppDataCaller = AppModel Function(AppModel app);

class AppController {
  static final AppController _instance = AppController._();

  late AppModel _app;

  String cacheKey = "app_data";

  Map<String, dynamic> config = {};

  factory AppController() => _instance;

  AppController._() {
    this._app = AppModel(false,
        User: UserModel("请先登录...", "assets/avatar/default.jpg"));
  }

  set Token(String? token) => _app.Token = token;

  bool get IsReadTips => _app.IsReadTips;

  //Token 用户token
  String? get Token => _app.Token ?? null;

  //IsLoginState 是否登录
  bool get IsLoginState => _app.IsLoginState;

  // User 获取用户
  UserModel? get User =>
      _app.User ?? UserModel("请先登录...", "assets/avatar/default.jpg");

  //storeAppData 储存并更新app信息
  Future<bool> storeAppDataAndSync({AppModel? app = null}) async {
    if (app == null) {
      app = this._app;
    }
    //储存到本地缓存
    var prefs = await SharedPreferences.getInstance();
    if (!await prefs.setString(this.cacheKey, app.toJsonString())) {
      BotToast.showSimpleNotification(title: "系统错误了,请重启app");
      return false;
    }
    //更新信息
    this._app = app;
    return true;
  }

  // storeAppDataAndSyncCaller 带回调的储存
  Future<bool> storeAppDataAndSyncCaller(AppDataCaller caller) async {
    return this.storeAppDataAndSync(app: caller(this._app));
  }

  //loadAppDataAndSync 加载并更新app信息
  Future<void> loadAppDataAndSync() async {
    try {
      var prefs = await SharedPreferences.getInstance();
      var appDataJsonStr = await prefs.getString(this.cacheKey);
      Logger().i("从本地读取的数据${appDataJsonStr}");
      if (appDataJsonStr != null) {
        var loadApp = AppModel.fromJson(json.decode(appDataJsonStr));
        //重新获取一次用户信息
        Logger().i("用户的token:${loadApp.Token}");

        if (loadApp.Token!.isNotEmpty) {
          try {
            loadApp.IsLoginState = false;
            loadApp.User = null;
            var response = await HttpClient().get(
              "/v1/user/profile",
              options: Options(
                headers: <String, dynamic>{
                  "Token": loadApp.Token,
                },
              ),
            );
            if (response.data['code'] == 1) {
              var data = response.data["data"];
              loadApp.User = UserModel.fromJson(data);
              loadApp.IsLoginState = true;
            }
          } catch (e) {}
        }

        this.storeAppDataAndSyncCaller((AppModel app) {
          return loadApp;
        });
      }
    } catch (e) {}
  }

  // cleanAppDataAndSync 清楚数据并同步app信息
  Future<bool> cleanAppDataAndSync() async {
    var prefs = await SharedPreferences.getInstance();
    if (!await prefs.remove(this.cacheKey)) {
      BotToast.showSimpleNotification(title: "推出登录失败了,请在设置里清理app数据");
      return false;
    }
    this._app = AppModel(false);
    return true;
  }

  //加载配置缓存
  Future<void> loadConfigAnd() async {
    CommonApi().init().then((response) async {
      if (response.data['code'] != 1) {
        BotToast.showText(text: response.data["msg"]);
        return;
      }
      var data = response.data["data"] as Map<String, dynamic>;
      for (var key in data.keys) {
        this.config[key] = data[key];
      }
    }).catchError((err) {
      BotToast.showText(text: err.toString());
    });
  }

  // getConfig 获取配置数据
  T getConfig<T>(String key, {dynamic def = null}) {
    if (this.config.containsKey(key)) {
      def = this.config[key];
    }
    return def;
  }
}
